/*
 * @Author: LiuYan
 * @Date: 2022-10-21 19:57:59
 * @LastEditors: LiuYan
 * @LastEditTime: 2022-11-13 17:04:43
 * @Description:
 */
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import * as app from "./src/config/index.js";
const { HTTP } = app.default;
import viteCompression from "vite-plugin-compression";
//  自动按需导入 element-plus
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import path from "path";
// https://vitejs.dev/config/ 使用defineConfig会有vite配置提示
export default defineConfig((n) => {
  return {
    plugins: [
      vue({
        reactivityTransform: true, //开启 ref 语法糖
      }),
      viteCompression({
        threshold: 1024000, // 对大于 1mb(1024000) 的文件进行压缩 ,0全部压缩
        deleteOriginFile: false, //压缩后是否删除原文件
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    base: "./",
    server: {
      open: false, //自动在浏览器中打开应用程序
      port: 8888,
      host: "127.0.0.1",
      https: false,
      proxy: {
        ...Object.assign(
          ...HTTP.cross_prefix.map((p) => {
            let item = {
              [p]: {
                target: HTTP.cross_domain,
                changeOrigin: true,
              },
            };
            return item;
          })
        ),
      },
    },
    //依赖优化项
    optimizeDeps: {
      //在与构建中，强制排除某依赖项. 建议不要强制排除依赖项，否则会造成网络拥堵导致记载变慢
      // exclude: ["axios"],
      include: [
        "element-plus/es/components/time-picker/style/css",
        "element-plus/es/components/button/style/css",
      ],
    },
    resolve: {
      //别名
      alias: {
        "@": path.resolve(__dirname, "./src/"),
        img: path.resolve(__dirname, "./src/assets/img/"),
      },
    },
    //打包相关配置
    build: {
      outDir: "dist", //打包路径
      reportCompressedSize: false, // gzip 压缩大小报告. 压缩大型输出文件可能会很慢，因此禁用该功能可能会提高大型项目的构建性能。
      //rollup打包配置
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              const arr = id.toString().split("node_modules/")[1].split("/");
              // 把第三方依赖包进行分片打包
              switch (arr[0]) {
                case "echarts":
                case "@vue":
                case "axios":
                case "animejs":
                case "vue-router":
                case "vuex":
                case "element-plus":
                  return "_" + arr[0];
                  break;
                default:
                  return "__vendor";
                  break;
              }
            }
          },
          chunkFileNames: "static/chunk/[name]-[hash].js",
          entryFileNames: "static/entry/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
        },
      },
    },
  };
});
